<template>
  <div>
    <section class="todoapp">
      <hm-header :list="list" @add-event="add"></hm-header>
      <hm-main
        :list="showlist"
        @remove-event="remove"
        @checked-event="checked"
        @change-event="change"
      ></hm-main>
      <hm-footer
        :list="list"
        :status="status"
        @clear-done-evrnt="clearDone"
        @show-stadus="selected"
      ></hm-footer>
    </section>
  </div>
</template>

<script>
const obj = {
  "#/": "all",
  "#/completed": "done",
  "#/active": "undone",
};
import HmHeader from "@/components/hm-header.vue";
import HmMain from "@/components/hm-main.vue";
import HmFooter from "@/components/hm-footer.vue";
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      list: JSON.parse(window.localStorage.getItem("list")) || [
        { id: 1, name: "起床", done: true },
        { id: 2, name: "吃饭", done: false },
        { id: 3, name: "睡觉", done: false },
      ],
      status: obj[location.hash] || "all", //all done undone
    };
  },
  methods: {
    //
    add(data) {
      this.list.push({ ...data });
    },
    remove(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    checked(value) {
      this.list.forEach((item) => (item.done = value));
    },
    change(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list[index].done = !this.list[index].done;
    },
    clearDone() {
      this.list = this.list.filter((item) => item.done === false);
    },
    selected(status) {
      this.status = status;
    },
  },
  computed: {
    showlist() {
      if (this.status === "all") {
        return this.list;
      } else if (this.status === "undone") {
        return this.list.filter((item) => item.done === false);
      } else {
        return this.list.filter((item) => item.done === true);
      }
    },
  },
  watch: {
    list: {
      handler(newValue) {
        window.localStorage.setItem("list", JSON.stringify(newValue));
      },
      deep: true,
    },
  },
};
</script>
